package com.shawn.example.mvvmdemo.home.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jetpack.mvvm.lib.common.modules.BaseStatus
import com.jetpack.mvvm.lib.net.module.HttpApiResult
import com.shawn.example.mvvmdemo.home.model.ArticleDetail
import com.shawn.example.mvvmdemo.home.model.Banner
import com.shawn.example.mvvmdemo.home.repository.HomeRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import okhttp3.internal.wait
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(app: Application) : AndroidViewModel(app) {
    companion object {
        private const val TAG = "HomeViewModel"
    }

    private val articleLiveData = MutableLiveData<List<ArticleDetail>>()
    private val bannerLiveData = MutableLiveData<List<Banner>>()
    private val loadingLiveData = MutableLiveData<BaseStatus>()

    val articleListLV: LiveData<List<ArticleDetail>> = articleLiveData
    val bannerLV: LiveData<List<Banner>> = bannerLiveData
    val loadingLV: LiveData<BaseStatus> = loadingLiveData

    @Inject
    lateinit var repository: HomeRepository

    fun getArticles(pageNum: Int = 0) = viewModelScope.launch {
        loadingLiveData.value = BaseStatus(isLoading = true)
        val topTask = async { repository.getTopArticles() }
        val listTask = async { repository.getArticles(pageNum) }
        withContext(Dispatchers.IO) {
            val result1 = topTask.await() as HttpApiResult<List<ArticleDetail>>
            val result2 = listTask.await()
            if (result1.isSuccess && result2.isSuccess) {
                val allArticles = mutableListOf<ArticleDetail>()
                val topArticles = (result1 as HttpApiResult.Success).value
                val articles = (result2 as HttpApiResult.Success).value
                topArticles.forEach {
                    it.top = "1"
                }
                allArticles.addAll(topArticles)
                allArticles.addAll(articles.datas)
                articleLiveData.postValue(allArticles)
                loadingLiveData.postValue(BaseStatus(isLoading = false))
            } else {
                loadingLiveData.postValue(BaseStatus(isLoading = false, isError = true))
            }
        }
    }

    fun getBanner() = viewModelScope.launch {
        val bannersResult = repository.getBanners()
        if (bannersResult.isSuccess) {
            bannerLiveData.value = (bannersResult as HttpApiResult.Success).value
        }
    }
}